<template>
  <PageWrapper class="virtual-scroll-demo">
    <div class="text-center mb-4">
      <a-input class="w-xs" v-model:value="sn" @change="snChange" />
      <a-button type="primary" @click="connect" class="mx-2">连接</a-button>
      <a-button @click="vScrollRef?.scrollToTop()">滚动到顶部</a-button>
      <a-button @click="vScrollRef?.scrollToBottom()" class="mx-2">滚动到底部</a-button>
      <a-button @click="vScrollRef?.scrollToItem(scrollToItemIndex)"
        >滚动到第
        <input-number
          v-model:value="scrollToItemIndex"
          class="!w-60px mx-1"
          :min="1"
          :max="list.length"
          :precision="0"
          size="small"
          :controls="false"
          @keydown.enter="vScrollRef?.scrollToItem(scrollToItemIndex)"
        />
        条
      </a-button>
    </div>
    <div class="virtual-scroll-demo-wrap">
      <VScroll :itemHeight="70" :items="list" :height="500" :width="300" ref="vScrollRef">
        <template #default="{ item }">
          <div class="virtual-scroll-demo__item" @click="clickItem(item)">
            {{ coder(item) }}
          </div>
        </template>
      </VScroll>
    </div>

    <div>raw</div>
    <CodeEditor v-model:value="rawValue" :mode="MODE.JSON" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { PageWrapper } from '@/components/Page';
  import { VScroll } from '@/components/VirtualScroll';
  import { InputNumber } from 'ant-design-vue';
  import { CodeEditor, MODE } from '@/components/CodeEditor';
  import { ref } from 'vue';
  import { Persistent } from '@/utils/cache/persistent';
  import { SN_KEY } from '@/enums/cacheEnum';
  import { getStompClient } from '@/utils/ws';

  const vScrollRef = ref<typeof VScroll>();
  const scrollToItemIndex = ref(1000);

  const list = ref([]);
  // const modeValue = ref<MODE>(MODE.JSON);
  const rawValue = ref('');

  let sn = ref<string>(Persistent.getLocal(SN_KEY) || '');
  let topic = ref<string>('/v1/sn/${sn}/realtimeLog');

  function snChange() {
    Persistent.setLocal(SN_KEY, sn.value);
  }

  function clickItem(item) {
    rawValue.value = item.logText;
  }

  function coder(item: any) {
    return item.logText;
  }

  async function connect() {
    let stompClient = await getStompClient();
    const subscribeTopic = topic.value.replace('${sn}', sn.value);
    console.log('subscribeTopic ', subscribeTopic);
    stompClient.subscribe(subscribeTopic, function (message) {
      console.log('subscribe have ', message);
      list.value.push(JSON.parse(message.body));
      vScrollRef.value.scrollToBottom();
    });
  }
</script>
<style lang="less" scoped>
  .virtual-scroll-demo {
    &-wrap {
      display: flex;
      justify-content: center;
      background-color: @component-background;
    }

    &__item {
      height: 60px;
      padding: 0 5px;
      margin-top: 10px;
      border-bottom: 1px solid @border-color-base;
      line-height: 8px;
    }
  }
</style>
